package com.example.lancooznbk.view.activity;

import android.content.Intent;
import android.graphics.Color;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.bumptech.glide.Glide;
import com.example.lancooznbk.R;
import com.example.lancooznbk.utils.ActivityUtil;
import com.example.lancooznbk.utils.DataCleanManager;
import com.example.lancooznbk.utils.DialogHelper;
import com.example.lancooznbk.view.adapter.HeaderBottomAdapter;
import com.example.lancooznbk.view.adapter.ListMenuOneAdapter;
import com.example.lancooznbk.view.adapter.ListMenuTwoAdapter;
import com.example.lancooznbk.view.base.BaseActivity;
import com.example.lancooznbk.view.widget.CircleImageView;
import com.example.lancooznbk.view.widget.CustomDialog;
import com.example.lancooznbk.view.widget.DisciplinePopWindow;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.lancoo.cpbase.authentication.activities.LoginActivity;
import com.lancoo.cpbase.authentication.base.LoginOperate;
import com.lancoo.reviewsystem.utils.ToastUtils;
import com.lancoo.rxretrofitlibrary.Api.UserInfo;

/**
 * Created by Administrator on 2018\1\25 0025.
 */

public class ZnbkMainActivity extends BaseActivity implements View.OnClickListener {

    /*
    * 左侧导航栏相关控件
    * */
    private CircleImageView mImgHead;
    private TextView mTvUserName;
    private TextView mTvUserClass;
    private TextView mTvUserNo;
    private LoginOperate mLoginOperate;
    private String strCacheSize;

    /*
    * 主界面顶部标题栏学科切换
    * */
    private TextView mTvDicName;
    private ImageView mArrowIv;
    private DisciplinePopWindow mDisciplinePopWindow;

    private View mView;
    private View mVmasker;
    private TextView mTvLoginOut;
    private SlidingMenu mMenu=null;

    /*
    * Recycler相关
    * */
    private RecyclerView mRecyclerView;
    private HeaderBottomAdapter adapter;
    LinearLayoutManager layoutManager;

    private XRefreshView mXRefreshView;

    private AppBarLayout mAppBarLayout;
    private CollapsingToolbarLayout collapsingToolbarLayout;


//    static Handler handler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what) {
//                case 0:
//                    ZnbkMainActivity activity = (ZnbkMainActivity) msg.obj;
//                    activity.mXRefreshView.setAutoRefresh(false);
//                    break;
//            }
//        }
//    };


    @Override
    public int attachLayoutRes() {
        return R.layout.znbk_slidingmenu_main;
    }

    @Override
    protected void initViews() {

        /*
        * 左侧侧滑导航栏
        * */
        mView=getLayoutInflater().inflate(R.layout.main_menu_login, null, false);

        mImgHead = (CircleImageView) mView.findViewById(R.id.img_userHead);
        mTvUserName = (TextView) mView.findViewById(R.id.tv_userName);
        mTvUserClass = (TextView) mView.findViewById(R.id.tv_userClass);
        mTvUserNo = (TextView) mView.findViewById(R.id.tv_userNo);

        Glide.with(this).load(UserInfo.PhotoUrl).skipMemoryCache(false).error(R.mipmap.img_head_default).into(mImgHead);
        mTvUserName.setText(UserInfo.StuName);
        mTvUserClass.setText(UserInfo.ClassName);
        mTvUserNo.setText(UserInfo.StuId);

        mLoginOperate = new LoginOperate(this);
        mTvLoginOut = (TextView) mView.findViewById(R.id.tv_login_out);
        mTvLoginOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLoginOperate.logOut();
                startActivity(new Intent(ZnbkMainActivity.this,LoginActivity.class));
                finish();
            }
        });


        /*
        * 学科切换
        * */
        mTvDicName = (TextView) findViewById(R.id.tv_discipline_name);
        mArrowIv = (ImageView) findViewById(R.id.iv_arrow);

        /*
        * Recycler
        * */
        mRecyclerView=(RecyclerView)findViewById(R.id.rv_main);
        //List布局
        layoutManager=new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter=new HeaderBottomAdapter(this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        mRecyclerView.setPadding(30,0,30,0);

        //下拉是刷新组件设置
        mXRefreshView = (XRefreshView) findViewById(R.id.sr_layout);

        //控制下拉loading出现与消失
        mAppBarLayout = (AppBarLayout) findViewById(R.id.appbar_layout);
        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

                if (verticalOffset >= 0) {
                    mXRefreshView.setEnabled(true);
                } else {
                    mXRefreshView.setEnabled(false);
                }
            }
        });


        initMenu(mView);
        initRightView();
        initToolbar();


    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    /*
    * 学科选择点击事件
    * */
    public void disciplineChoiceClick(View view) {
        mDisciplinePopWindow = new DisciplinePopWindow(ZnbkMainActivity.this,mTvDicName,mArrowIv,view);
        mDisciplinePopWindow.setClippingEnabled(false);//使popupwindow显示为全屏
        mDisciplinePopWindow.showAtLocation(mArrowIv, Gravity.TOP, 0, 10);
    }


    private void initRightView() {

        ImageView mImageView=(ImageView) findViewById(R.id.iv_personal_icon);
        mImageView.setOnClickListener(ZnbkMainActivity.this);

        mVmasker = (View) findViewById(R.id.view_masker);

    }

    private void initLeftListView(View view) {
        ListView listView1=(ListView) view.findViewById(R.id.listview_menu);
        listView1.setAdapter(new ListMenuOneAdapter(ZnbkMainActivity.this));
        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                switch (i) {
                    case 0:
                        ToastUtils.showShort( "点击了 id=" + i);
                        break;
                    case 1:
                        ToastUtils.showShort( "点击了 id=" + i);
                        break;
                    case 2:
                        ToastUtils.showShort( "点击了 id=" + i+"系统说明");
                        SystemHelperActivity.launch(ZnbkMainActivity.this);
                        break;
                }
            }
        });


        ListView listView2=(ListView) view.findViewById(R.id.listview_menu_two);
        listView2.setAdapter(new ListMenuTwoAdapter(ZnbkMainActivity.this));
        listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                switch (i) {
                    case 0:
                        ToastUtils.showShort( "点击了 id=" + i+"清理缓存");
                        try {
                            strCacheSize = DataCleanManager.getCacheSize(ZnbkMainActivity.this);
                        } catch (Exception e) {
                            e.printStackTrace();
                            strCacheSize = "系统异常！";
                        }

                        DialogHelper.cleanCacheDialog(ZnbkMainActivity.this, strCacheSize,new CustomDialog.OnCustomClickListener() {
                            @Override
                            public void onClick() {
                                DataCleanManager.cleanInternalCache(ZnbkMainActivity.this);
                            }
                        });
                        break;
                    case 1:
                        ToastUtils.showShort( "点击了 id=" + i);
                        break;
                }
            }
        });

    }


    /*
    * 标题栏头像侧滑点击功能
    * */
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_personal_icon:
                mMenu.showMenu();
                break;
        }
    }


    /*
    * 初始化侧滑功能
    * */
    private void initMenu(View view) {
        mMenu=(SlidingMenu) findViewById(R.id.slidingmenulayout);
        mMenu.setMode(SlidingMenu.LEFT);
        // 设置触摸屏幕的模式
        mMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
        //获取屏幕宽高
        DisplayMetrics dm=new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        // 设置滑动菜单视图的宽度
        mMenu.setBehindWidth(dm.widthPixels * 4 / 5);
        // 设置渐入渐出效果的值
        mMenu.setFadeDegree(0.35f);
        mMenu.setMenu(view);
        initLeftListView(view);//初始化侧边视图

        mMenu.setOnOpenListener(new SlidingMenu.OnOpenListener() {
            @Override
            public void onOpen() {
                mVmasker.setVisibility(View.VISIBLE);
            }
        });

        mMenu.setOnClosedListener(new SlidingMenu.OnClosedListener() {
            @Override
            public void onClosed() {
                mVmasker.setVisibility(View.GONE);
            }
        });

    }

    /**
     * 初始化工具栏
     */
    public void initToolbar() {
        collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_layout);
        //设置Titlebar title 展开时title 位置
        collapsingToolbarLayout.setExpandedTitleGravity(Gravity.NO_GRAVITY);
        //设置Titlebar title 折叠后title 位置
        collapsingToolbarLayout.setCollapsedTitleGravity(Gravity.CENTER_HORIZONTAL);
        //设置Titlebar title 折叠后字体颜色
        collapsingToolbarLayout.setCollapsedTitleTextColor(Color.WHITE);
        //设置Titlebar title 展开后字体颜色
        collapsingToolbarLayout.setExpandedTitleColor(Color.parseColor("#00000000"));
        //设置折叠后titlebar颜色(透明)
//        collapsingToolbarLayout.setContentScrimColor(Color.parseColor("#99FF0000"));
        collapsingToolbarLayout.setContentScrimColor(Color.parseColor("#00000000"));
        //设置title 是否可以被展开
        collapsingToolbarLayout.setTitleEnabled(true);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        //设置显示返回按钮 返回按钮的监听需在onOptionsItemSelected(MenuItem item) 方法中进行监听 返回按钮ID：android.R.id.home
        actionBar.setDisplayHomeAsUpEnabled(true);
        //设置是否显示titlebar title 默认为true 默认显示项目名称
        actionBar.setDisplayShowTitleEnabled(true);
        //自定义显示title内容
        actionBar.setTitle("ZNBK");

        actionBar.setDisplayHomeAsUpEnabled(false);
    }


    //按两次退出应用
    private long mExitTime;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {

            if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
                    mExitTime = System.currentTimeMillis();
                } else {
                    ActivityUtil.getInstance().AppExit();
                }
            }


            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

//    @Override
//    public void onRefresh() {
//        new Timer().schedule(new TimerTask() {
//            @Override
//            public void run() {
//                Message msg = ZnbkMainActivity.handler.obtainMessage();
//                msg.obj = ZnbkMainActivity.this;
//                msg.what = 0;
//                ZnbkMainActivity.handler.sendMessage(msg);
//            }
//        }, 2000);
//    }
}
